package com.macrohard.admin.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macrohard.admin.domain.StudentExcelModel;
import com.macrohard.admin.service.StudentsService;
import com.macrohard.admin.utils.poi.ExcelUtil;
import com.macrohard.common.base.response.R;
import com.macrohard.mapper.domain.Students;
import com.macrohard.mapper.domain.Teacher;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("student")
@Validated
@Api(tags = "学生接口")
@RequiredArgsConstructor
public class StudentController {

	private final StudentsService studentsService;

	@GetMapping
	@ApiOperation("分页获取所有学生")
	public R get(@NotNull Integer current, @NotNull Integer pageSize) {
		Page<Students> page = new Page<>(current, pageSize);
		LambdaQueryWrapper<Students> queryWrapper = new LambdaQueryWrapper<>();
		page = studentsService.page(page, queryWrapper);
		return R.ok("ok", page);
	}

	@ApiOperation("根据id获取学生")
	@GetMapping("{id}")
	public R get(@PathVariable Integer id) {
		return R.ok("ok", studentsService.getById(id));
	}

	@ApiOperation("添加学生")
	@PostMapping
	public R add(@RequestBody Students student) {
		return R.wrapEffectResult(studentsService.save(student));
	}

	@PutMapping
	@ApiOperation("修改学生")
	public R update(@RequestBody Students student) {
		return R.wrapEffectResult(studentsService.updateById(student));
	}

	@ApiOperation("根据id删除学生")
	@DeleteMapping("{id}")
	public R delete(@PathVariable Integer id) {
		return R.wrapEffectResult(studentsService.removeById(id));
	}

	@ApiOperation("批量删除学生")
	@DeleteMapping
	public R delete(@RequestBody List<Integer> ids) {
		return R.wrapEffectResult(studentsService.removeByIds(ids));
	}

	@GetMapping("excel")
	public void download(HttpServletResponse response) {
		List<StudentExcelModel> list = studentsService.list().stream().map(StudentExcelModel::new).collect(Collectors.toList());
		ExcelUtil.exportExcel(list, "学生信息", StudentExcelModel.class, response);
	}
}
